package com.cbgolf.oa.views;

import static com.cbgolf.oa.R.id.a_statistics_linechart_name_tv;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Matrix;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.ArrayMap;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.cbgolf.oa.R;
import com.cbgolf.oa.base.BaseView;
import com.cbgolf.oa.entity.ChartBean;
import com.cbgolf.oa.entity.ChartData;
import com.cbgolf.oa.entity.ChartData.CaddieHistory;
import com.cbgolf.oa.entity.DateRange;
import com.cbgolf.oa.entity.ListBean;
import com.cbgolf.oa.entity.PointBean;
import com.cbgolf.oa.entity.StatisticsBean;
import com.cbgolf.oa.manager.DataManager;
import com.cbgolf.oa.presenter.IStatisticsPresenter;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.CollectionUtil;
import com.cbgolf.oa.util.DataUtil;
import com.cbgolf.oa.util.DateUtil;
import com.cbgolf.oa.util.EnumUtil;
import com.cbgolf.oa.util.ErrorUtil;
import com.cbgolf.oa.util.PopUtil;
import com.cbgolf.oa.util.TextUtil;
import com.cbgolf.oa.util.TypeUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.util.ViewUtils;
import com.cbgolf.oa.widget.MyMarkerView;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.components.YAxis.AxisDependency;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.LargeValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.MPPointD;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.xutils.view.annotation.ViewInject;

/**
 * @author lq
 * @date 2017/9/13
 */

public class StatisticsView extends BaseView {

  //top
  @ViewInject(R.id.topBack_ll)
  private View topBack;
  @ViewInject(R.id.title_tv)
  private TextView topTitle;
  //body
  @ViewInject(R.id.a_statistics_name_tv)
  private TextView qiuChangNameTv;
  @ViewInject(R.id.a_statistics_yingyedian_filter_ll)
  private View filterPointView;
  @ViewInject(R.id.a_statistics_yingyedian_tv)
  private TextView filterPointTv;
  @ViewInject(R.id.a_statistics_filter_date_type_ll)
  private View filterDateView;
  @ViewInject(R.id.a_statistics_filter_date_type_tv)
  private TextView filterDateTv;
  @ViewInject(R.id.a_statistics_date_last_tv)
  private TextView lastTv;
  @ViewInject(R.id.a_statistics_date_tv)
  private TextView dateTv;
  @ViewInject(R.id.a_statistics_date_next_tv)
  private TextView nextTv;
  //
  @ViewInject(R.id.a_statistics_date_ll)
  private View dateTypeChooseView;
  @ViewInject(R.id.a_statistics_day_tv)
  private TextView dayTv;
  @ViewInject(R.id.a_statistics_week_tv)
  private TextView weekTv;
  @ViewInject(R.id.a_statistics_month_tv)
  private TextView monthTv;
  @ViewInject(R.id.a_statistics_quarter_tv)
  private TextView quarterTv;
  @ViewInject(R.id.a_statistics_year_tv)
  private TextView yearTv;
  //money
  @ViewInject(R.id.a_statistics_money_all_tv)
  private TextView allNumTv;
  @ViewInject(R.id.a_statistics_money_all_compare_tv)
  private TextView allCompareTv;
  @ViewInject(R.id.a_statistics_money_jiru_tv)
  private TextView inCludeNumTv;
  @ViewInject(R.id.a_statistics_money_jiru_compare_tv)
  private TextView inCludeCompareTv;
  @ViewInject(R.id.a_statistics_money_not_clude_tv)
  private TextView noCludeNumTv;
  @ViewInject(R.id.a_statistics_money_not_clude_compare_tv)
  private TextView noCludeCompareTv;
  //chart
  @ViewInject(R.id.a_statistics_money_this_tv)
  private TextView thisNumTv;
  @ViewInject(R.id.a_statistics_money_this_compare_tv)
  private TextView thisCompareTv;
  @ViewInject(R.id.a_statistics_money_linechart)
  private LineChart lineChart;
  @ViewInject(R.id.a_statistics_pay_type_barchart)
  private BarChart barChart;
  //
  @ViewInject(R.id.a_statistics_all_ll)
  private View allView;
  @ViewInject(R.id.a_statistics_include_ll)
  private View includeView;
  @ViewInject(R.id.a_statistics_not_include_ll)
  private View notIncludeView;
  //name
  @ViewInject(R.id.a_statistics_all_name_tv)
  private TextView allNameTv;
  @ViewInject(R.id.a_statistics_include_name_tv)
  private TextView includeNameTv;
  @ViewInject(R.id.a_statistics_not_include_name_tv)
  private TextView notIncludeNameTv;
  @ViewInject(a_statistics_linechart_name_tv)
  private TextView lineChartNameTv;
  @ViewInject(R.id.a_statistics_barchart_name_tv)
  private TextView barChartNameTv;
  //
  @ViewInject(R.id.a_statistics_linechart_this_tv)
  private TextView lineThisTv;
  @ViewInject(R.id.a_statistics_linechart_last_tv)
  private TextView lineLastTv;
  @ViewInject(R.id.a_statistics_barchart_this_tv)
  private TextView barThisTv;
  @ViewInject(R.id.a_statistics_barchart_last_tv)
  private TextView barLastTv;

  @ViewInject(R.id.a_statistics_order_tv)
  private TextView barInfoTv;
//    @ViewInject(R.id.gridview)
//    private GridView gridView;

  //var
  private final int ALLTYPE = 0;
  private final int INCLUDE = 1;
  private final int NOTINCLUDE = 2;
  /**
   * 数据类型 全部，包含 ，不包含
   */
  private int dataChooseType = ALLTYPE;
  private final int CUR = 0;
  private final int DAY = CUR + 1;
  private final int WEEK = DAY + 1;
  private final int MONTH = WEEK + 1;
  private final int QUARTER = MONTH + 1;
  private final int YEAR = QUARTER + 1;
  /**
   * 日期类型
   */
  private int dateType = CUR;
  String[] weeks = new String[]{
      "", "周一", "周二", "周三", "周四", "周五", "周六", "周日",
  };

  int startStep = 1000;
  private String mDateString;
  private String pointCode;

  private IStatisticsPresenter worker;
  private int mType;

  public StatisticsView(Activity act, IStatisticsPresenter worker, int type) {
    this.worker = worker;
    this.mType = type;
    ViewUtils.autoInjectAllField(this, act);
    super.init(act);

  }

  @Override
  protected void setViews() {
    qiuChangNameTv.setText(worker.getActivityTitle());
    mDateString = DateUtil.stampToDate(System.currentTimeMillis(), DateUtil.formatYMD);
    dateTv.setText(mDateString);
    setNextTvLive(false);
    lineChart.setNoDataText(ErrorUtil.NODATA);
    barChart.setNoDataText(ErrorUtil.NODATA);
    lineChart.setNoDataTextColor(ContextCompat.getColor(context, R.color.text_gray));
    barChart.setNoDataTextColor(ContextCompat.getColor(context, R.color.text_gray));
  }

  public void setNextTvLive(boolean isLive) {
    nextTv.setEnabled(isLive);
    nextTv.setTextColor(isLive ? ContextCompat.getColor(context, R.color.bg_blue)
        : ContextCompat.getColor(context, R.color.text_hint));
  }

  public void setViewInfo() {
    switch (mType) {
      case DataManager.STATISTICS_BUSINESS_ALL:
        topTitle.setText("营业统计");
        worker.getPointList();
        break;
      case DataManager.STATISTICS_BOOK_ALL:
        topTitle.setText("预订统计");
        filterPointView.setVisibility(View.GONE);
        allNameTv.setText("总预订(人)");
        includeNameTv.setText("到场(人)");
        notIncludeNameTv.setText("未到场(人)");
        lineChartNameTv.setText("预订人数");
        barChartNameTv.setText("预订渠道");
        break;
      case DataManager.STATISTICS_CADDIE_ALL:
        topTitle.setText("球僮出场统计");
        filterPointView.setVisibility(View.GONE);
        allNameTv.setText("总出场次(次)");
        includeNameTv.setText("平均场次(次)");
        notIncludeNameTv.setText("平均时长(分钟)");
        lineChartNameTv.setText("出场人次");
        barChartNameTv.setText("出场次数");
        setBackroundGradient();
        break;
      case DataManager.STATISTICS_BILL_ALL:
        topTitle.setText("签单统计");
        allNameTv.setText("签单总额(元)");
        includeNameTv.setText("会员(元)");
        notIncludeNameTv.setText("非会员(元)");
        lineChartNameTv.setText("签单费用");
        barChartNameTv.setText("签单人");
        nextTv.setText("后一周");
        lastTv.setText("上一周");
        lineThisTv.setText("本周");
        lineLastTv.setText("上周");
        barThisTv.setText("本周");
        barLastTv.setText("上周");
        mDateString = "本周";
        dateTv.setText(mDateString);
        dayTv.setVisibility(View.GONE);
        quarterTv.setVisibility(View.GONE);
        filterPointView.setVisibility(View.GONE);
        setBackroundGradient();
        worker.getPointList();
        break;
      case DataManager.STATISTICS_PLAYER_ALL:
        ViewUtils.setText(topTitle, "打球人统计");
        allNameTv.setText("总人数(人)");
        includeNameTv.setText("下场人数(人)");
        notIncludeNameTv.setText("未下场人数(人)");
        lineChartNameTv.setText("到场总人次");
        barChartNameTv.setText("身份");
        filterPointView.setVisibility(View.GONE);
//        setBackroundGradient();
        worker.getPointList();
        break;
      default:
        break;
    }
    setNumDatas(new ChartBean());
  }

  private void setBackroundGradient() {
    allView.setBackgroundResource(R.drawable.gradient_blue_todeep_round5_hori);
    includeView.setBackgroundResource(R.drawable.gradient_blue_todeep_round5_hori);
    notIncludeView.setBackgroundResource(R.drawable.gradient_blue_todeep_round5_hori);
    allView.setEnabled(false);
    includeView.setEnabled(false);
    notIncludeView.setEnabled(false);
  }

  public void setNumDatas(ChartBean bean) {
    if (mType == DataManager.STATISTICS_BOOK_ALL || mType == DataManager.STATISTICS_PLAYER_ALL) {
      allNumTv.setText(TextUtil.textNumInt(TypeUtil.getInt(bean.allNum)));
      inCludeNumTv.setText(TextUtil.textNumInt(TypeUtil.getInt(bean.inNum)));
      noCludeNumTv.setText(TextUtil.textNumInt(TypeUtil.getInt(bean.noCludeNum)));
    } else {
      allNumTv.setText(TextUtil.textNumFloat(bean.allNum, 2));
      inCludeNumTv.setText(TextUtil.textNumFloat(bean.inNum, 2));
      noCludeNumTv.setText(TextUtil.textNumFloat(bean.noCludeNum, 2));
    }

    allCompareTv.setText(Util.isNull(bean.allRatio) ? "" : bean.allRatio);
    inCludeCompareTv.setText(Util.isNull(bean.inRatio) ? "" : bean.inRatio);
    noCludeCompareTv.setText(Util.isNull(bean.noCludeRatio) ? "" : bean.noCludeRatio);
    String unit = EnumUtil.getStatisticsUnit(mType);
    switch (dataChooseType) {
      case ALLTYPE:
        thisNumTv.setText((allNumTv.getText().toString() + unit));
        thisCompareTv.setText(allCompareTv.getText().toString());
        break;
      case INCLUDE:
        thisNumTv.setText((inCludeNumTv.getText().toString() + unit));
        thisCompareTv.setText(inCludeCompareTv.getText().toString());
        break;
      case NOTINCLUDE:
        if (mType == DataManager.STATISTICS_CADDIE_ALL) {
          thisNumTv.setText((noCludeNumTv.getText().toString() + "分"));
        } else {
          thisNumTv.setText((noCludeNumTv.getText().toString() + unit));
        }
        thisCompareTv.setText(noCludeCompareTv.getText().toString());
        break;
      default:
        thisNumTv.setText("");
        thisCompareTv.setText("");
        break;
    }
  }

  private List<PointBean> listPoint = new ArrayList<>();
  private boolean pointIsFail;

  public void setPointData(Object list) {
    listPoint = (List<PointBean>) list;
  }

  public void setPointFail() {
    pointIsFail = true;
  }


  @Override
  protected void setListener() {
    topBack.setOnClickListener(v -> context.finish());
//    orderTv.setOnClickListener(v -> worker.ClickShowOrder());
    filterPointView.setOnClickListener(v -> {
      if (View.VISIBLE == dateTypeChooseView.getVisibility()) {
        dateTypeChooseView.setVisibility(View.GONE);
      }
      if (pointIsFail) {
        Util.show("营业点获取失败");
        return;
      }
      if (Util.listIsNull(listPoint)) {
        Util.show("没有营业点");
        return;
      }
      PopUtil.setPopWidthAndHeight(0, 0);
      final List<PointBean> list = new ArrayList<>();
      String name = filterPointTv.getText().toString();
      for (int i = 0; i < listPoint.size(); i++) {
        if (!Util.isEquals(name, listPoint.get(i).name)) {
          list.add(listPoint.get(i));
        }
      }
      if (!Util.isEquals("所有营业点", name)) {
        PointBean m = new PointBean();
        m.code = "";
        m.name = "所有营业点";
        list.add(m);
      }
      PopUtil.showPointFilterList(context, filterPointView, list,
          position -> {
            filterPointTv.setText(list.get(position).name);
            pointCode = list.get(position).code;
            worker.setPoint(pointCode);
            if (mType == DataManager.STATISTICS_BUSINESS_ALL) {
              worker.getBussinessData();
            } else {
              worker.getBillData();
            }
          });
    });
    filterDateView.setOnClickListener(v -> {

      if (View.VISIBLE == dateTypeChooseView.getVisibility()) {
        dateTypeChooseView.setVisibility(View.GONE);
      } else {

        dateTypeChooseView.setVisibility(View.VISIBLE);
      }
    });
    dayTv.setOnClickListener(v -> {
      dateType = DAY;
      mDateString = DateUtil.stampToDate(System.currentTimeMillis(), DateUtil.formatYMD);
      getFilterData();
    });
    weekTv.setOnClickListener(v -> {
      dateType = WEEK;
      mDateString = "本周";
      getFilterData();
    });
    monthTv.setOnClickListener(v -> {
      dateType = MONTH;
      mDateString = "本月";
      getFilterData();

    });
    quarterTv.setOnClickListener(v -> {
      dateType = QUARTER;
      mDateString = "本季度";
      getFilterData();
    });
    yearTv.setOnClickListener(v -> {
      dateType = YEAR;
      mDateString = "今年";
      getFilterData();
    });
    lastTv.setOnClickListener(v -> {
      if (View.VISIBLE == dateTypeChooseView.getVisibility()) {
        dateTypeChooseView.setVisibility(View.GONE);
      }
      if (!nextTv.isEnabled()) {
        setNextTvLive(true);
      }
      worker.getLast(dateType, dataChooseType);
    });
    nextTv.setOnClickListener(v -> {
      if (View.VISIBLE == dateTypeChooseView.getVisibility()) {
        dateTypeChooseView.setVisibility(View.GONE);
      }
      worker.getNext(dateType, dataChooseType);
    });
    allView.setOnClickListener(v -> {
      if (dataChooseType == ALLTYPE) {
        return;
      }
      dataChooseType = ALLTYPE;
      setDataTypeChooseView();

    });
    notIncludeView.setOnClickListener(v -> {
      if (dataChooseType == NOTINCLUDE) {
        return;
      }
      dataChooseType = NOTINCLUDE;
      setDataTypeChooseView();

    });
    includeView.setOnClickListener(v -> {
      if (dataChooseType == INCLUDE) {
        return;
      }
      dataChooseType = INCLUDE;
      setDataTypeChooseView();

    });
  }

  private void setDataTypeChooseView() {
    resetBackground();
    switch (dataChooseType) {
      case ALLTYPE:
        allView.setBackgroundResource(R.drawable.gradient_blue_todeep_round5_hori);
        thisNumTv.setText(allNumTv.getText().toString());
        thisCompareTv.setText(allCompareTv.getText().toString());
        if (mType == DataManager.STATISTICS_BOOK_ALL) {
          lineChartNameTv.setText("预订人数");
        } else if (mType == DataManager.STATISTICS_BILL_ALL) {
          lineChartNameTv.setText("签单总额");
        }
        break;
      case INCLUDE:
        includeView.setBackgroundResource(R.drawable.gradient_blue_todeep_round5_hori);
        thisNumTv.setText(inCludeNumTv.getText().toString());
        thisCompareTv.setText(inCludeCompareTv.getText().toString());
        if (mType == DataManager.STATISTICS_BOOK_ALL) {
          lineChartNameTv.setText("到场人数");
        } else if (mType == DataManager.STATISTICS_BILL_ALL) {
          lineChartNameTv.setText("访客");
        }
        break;
      case NOTINCLUDE:
        notIncludeView.setBackgroundResource(R.drawable.gradient_blue_todeep_round5_hori);
        thisNumTv.setText(noCludeNumTv.getText().toString());
        thisCompareTv.setText(noCludeCompareTv.getText().toString());
        if (mType == DataManager.STATISTICS_BOOK_ALL) {
          lineChartNameTv.setText("未到场人数");
        } else if (mType == DataManager.STATISTICS_BILL_ALL) {
          lineChartNameTv.setText("非访客");
        }
        break;
      default:
        break;
    }
    worker.getChooseTypeData(dateType, dataChooseType);
  }

  private void resetBackground() {
    allView.setBackgroundResource(R.drawable.bg_blue_light_round5);
    includeView.setBackgroundResource(R.drawable.bg_blue_light_round5);
    notIncludeView.setBackgroundResource(R.drawable.bg_blue_light_round5);
  }

  private void getFilterData() {
    worker.getFilterData(dateType, dataChooseType);

  }

  private String[] filterTypes = new String[]{
      "天", "天", "周", "月", "季", "年"
  };

  public void setFilterViews(int dateType) {
    filterDateTv.setText(("按" + filterTypes[dateType] + "查看"));
    TextView[] tvs = new TextView[]{
        dateTv, lastTv, nextTv, lineThisTv, lineLastTv, barThisTv, barLastTv
    };
    String[] dayText = new String[]{
        DateUtil.stampToDateyMd3(String.valueOf(System.currentTimeMillis())),
        "前一天", "后一天", "当日", "上日", "当日", "上日"
    };
    String[] weekText = new String[]{
        "本周", "上一周", "下一周", "本周", "上周", "本周", "上周"
    };
    String[] quarterText = new String[]{
        "本季度", "上季度", "下季度", "本季度", "上季度", "本季度", "上季度"
    };
    switch (dateType) {
      case DAY:
        for (int i = 0; i < tvs.length; i++) {
          tvs[i].setText(dayText[i]);
        }
        break;
      case WEEK:
        for (int i = 0; i < tvs.length; i++) {
          tvs[i].setText(weekText[i]);
        }

        break;
      case MONTH:
        for (int i = 0; i < tvs.length; i++) {
          tvs[i].setText(weekText[i].replace("周", "月"));
        }

        break;
      case QUARTER:
        for (int i = 0; i < tvs.length; i++) {
          tvs[i].setText(quarterText[i]);
        }

        break;
      case YEAR:
        for (int i = 0; i < tvs.length; i++) {
          if (i == 0) {
            tvs[i].setText("今年");
            continue;
          }
          tvs[i].setText(weekText[i].replace("周", "年"));
        }
        break;
      default:
        break;
    }
    dateTypeChooseView.setVisibility(View.GONE);
  }

  public void reset() {
    lineChart.clear();
    barChart.clear();
    lineChart.notifyDataSetChanged();
    barChart.notifyDataSetChanged();
    allNumTv.setText("");
    allCompareTv.setText("");
    inCludeNumTv.setText("");
    inCludeCompareTv.setText("");
    noCludeNumTv.setText("");
    noCludeCompareTv.setText("");
    thisNumTv.setText("");
    thisCompareTv.setText("");
//        thisYearPawWayVals.clear();
//        thisYearVals.clear();
//        lastYearVals.clear();
//        lastYearPawWayVals.clear();
//        payNameMap.clear();
  }

  public void showError(String msg) {
    stopLoading();
    if (Util.isEquals(msg, ErrorUtil.NETERROR)) {
      lineChart.setNoDataText("部分时间段未有数据或数据维护中，请选择其他时间。");
      barChart.setNoDataText("部分时间段未有数据或数据维护中，请选择其他时间。");
    } else {
      lineChart.setNoDataText(TextUtil.Text(msg));
      barChart.setNoDataText(TextUtil.Text(msg));
    }
//    if (mType == DataManager.STATISTICS_BILL_ALL) {
//      orderTv.setVisibility(View.GONE);
//    }
    lineChart.clear();
    barChart.clear();
    lineChart.invalidate();
    barChart.invalidate();
  }

  public void showLoading() {
//        AnimaUtil.showLoading(context);
    lineChart.setNoDataText("加载中...");
    barChart.setNoDataText("加载中...");
  }

  public void stopLoading() {
    AnimaUtil.stopLoading();
  }


  public void setDate(String date) {
    mDateString = date;
    Log.e("dateString----------", mDateString + "---");
    dateTv.setText(TextUtil.Text(date));
  }

  public void setChartData(ChartBean bean) {
    this.dateType = bean.dateType;
//        setLinChar(lineChart, bean);
//        setBarChart(barChart, bean);
    stopLoading();
    initLineChart(bean);
    setLinChartData(bean);
    initBarChart(bean);
    setBarChartData(bean);
  }

  public void initLineChart(ChartBean bean) {
//    lineChart.setOnChartValueSelectedListener(new CharValueListener());
    // no description text
    lineChart.getDescription().setEnabled(false);
    // enable touch gestures
//        lineChart.setTouchEnabled(false);
    lineChart.setDrawBorders(false);
    lineChart.setDragDecelerationFrictionCoef(0.9f);
    // enable scaling and dragging
//        lineChart.setDragEnabled(false);
//        lineChart.setScaleEnabled(true);
    lineChart.setDrawGridBackground(false);
    lineChart.setHighlightPerDragEnabled(false);

    //设置chart是否可以触摸
    lineChart.setTouchEnabled(true);
    //设置是否可以拖拽
    lineChart.setDragEnabled(true);
    //设置是否可以缩放 x和y，默认true
    lineChart.setScaleEnabled(true);
    //是否缩放X轴
    lineChart.setScaleXEnabled(false);
    //X轴缩放比例
//        lineChart.setScaleX(1.5f);
    //Y轴缩放比例
//        lineChart.setScaleY(1.5f);
    //是否缩放Y轴
    lineChart.setScaleYEnabled(true);
    //设置是否可以通过双击屏幕放大图表。默认是true
    lineChart.setDoubleTapToZoomEnabled(false);

    // if disabled, scaling can be done on x- and y-axis separately
    lineChart.setPinchZoom(true);
    // set an alternative background color
    lineChart.setBackgroundColor(ContextCompat.getColor(context, R.color.transparent));

    // add data
    lineChart.animateX(1500);
    // get the legend (only possible after setting data)
    Legend l = lineChart.getLegend();
    // modify the legend ...
    l.setForm(Legend.LegendForm.LINE);
//        l.setTypeface(mTfLight);
    l.setTextSize(11f);
    l.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
    l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
    l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
    l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
    l.setDrawInside(false);
    lineChart.getLegend().setEnabled(false); //设置表头不可用
    lineChart.setHardwareAccelerationEnabled(true);
//        l.setYOffset(11f);
//        l.setXOffset(1f);
    XAxis xAxis = lineChart.getXAxis();
//        xAxis.setTypeface(mTfLight);
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
    xAxis.setTextSize(11f);
    xAxis.setAvoidFirstLastClipping(true);
    xAxis.resetAxisMaximum();
    xAxis.resetAxisMinimum();
    xAxis.setAxisMinimum(bean.lineXMin);
    xAxis.setAxisMaximum(bean.lineXMax);
    xAxis.setLabelCount(bean.lineXLableCount, true);
    xAxis.setValueFormatter(new LinFormat());
    xAxis.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
    // 设置X轴启用或者禁用
    xAxis.setEnabled(true);
    // 上面第一行代码设置了false,所以下面第一行即使设置为true也不会绘制AxisLine
    xAxis.setDrawLabels(true);
    //设置x轴的字体
//        xAxis.setTypeface(mTf);
    //是否绘制x轴的网格线
    xAxis.setDrawGridLines(false);
    //是否绘制x轴的轴线
    xAxis.setDrawAxisLine(true);
    //设置x轴坐标的间距
//        xAxis.setSpaceBetweenLabels(16);
    //定制X轴起点和终点Label不能超出屏幕。

    YAxis leftAxis = lineChart.getAxisLeft();
//        leftAxis.setTypeface(mTfLight);
//        leftAxis.setTextColor(ColorTemplate.getHoloBlue());
    leftAxis.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
    leftAxis.setDrawGridLines(true);
//        leftAxis.setGridColor(ContextCompat.getColor(context, R.color.text_gray));
    leftAxis.setGranularityEnabled(false);
    leftAxis.setDrawLimitLinesBehindData(true);
    //是否启用左边Y轴
    leftAxis.setEnabled(true);
    //设置最小值（这里就按demo里固死的写）
    leftAxis.setAxisMinimum(0);
    //设置最大值（这里就按demo里固死的写了）
//        leftAxis.setAxisMaximum((bean.lineLeftMax/100 +1)*100);
//        Log.e("line--------left", bean.lineLeftMax + "");
//        leftAxis.setAxisMaximum(bean.lineLeftMax);
//        leftAxis.setAxisMaximum(2235 + 100);
    //设置横向的线为虚线
//        leftAxis.enableGridDashedLine(10f, 10f, 0f);
    //设置左边y轴的字体
//        leftAxis.setTypeface(mTf);
    //参数1：左边y轴提供的区间的个数。 参数2：是否均匀分布这几个区间。 false：均匀。 true：不均匀
    leftAxis.setLabelCount(bean.lineYLableCount, true);
//        leftAxis.setValueFormatter(new MyYAxisValueFormatter());
    leftAxis.setDrawAxisLine(false);
    leftAxis.setDrawZeroLine(true);
    leftAxis.setZeroLineColor(ContextCompat.getColor(context, R.color.text_gray));
    leftAxis.setSpaceTop(20f);
    YAxis rightAxis = lineChart.getAxisRight();
    rightAxis.setEnabled(false);
    rightAxis.setDrawLabels(false);

//        rightAxis.setTextColor(Color.RED);
    rightAxis.setAxisMaximum(bean.lineLeftMax + 100);
    rightAxis.setAxisMinimum(0);
    rightAxis.setDrawGridLines(true);
    rightAxis.setDrawZeroLine(false);
    rightAxis.setGranularityEnabled(false);
//        rightAxis.enableGridDashedLine(10f, 10f, 0f);
    //=================设置左边Y轴===============

  }

//    ArrayList<Entry> thisYearVals = new ArrayList<Entry>();
//    ArrayList<Entry> lastYearVals = new ArrayList<Entry>();
//    ArrayList<BarEntry> thisYearPawWayVals = new ArrayList<BarEntry>();
//    ArrayList<BarEntry> lastYearPawWayVals = new ArrayList<BarEntry>();
//    Map<Integer, String> payNameMap = new HashMap<>();

  public static void setLineDefaultData(List<Entry> list, Entry entry) {
    if (null == list) {
      list = new ArrayList<>();
    }
    if (list.size() == 0) {
      list.add(entry);
    }
  }

  public static void setBarDefaultData(List<BarEntry> list, BarEntry entry) {
    if (null == list) {
      list = new ArrayList<>();
    }
    if (list.size() == 0) {
      list.add(entry);
    }
  }

  private void setLinChartData(ChartBean bean) {

    ArrayList<Entry> lineThis = bean.LinethisVals;
    ArrayList<Entry> lineLast = bean.LinelastVals;
//        final TreeMap<Integer, String> names = bean.lineNames;
    if (Util.listIsNull(lineThis)
        && Util.listIsNull(lineLast)) {
      showError(ErrorUtil.NODATA);
      return;
    }
    setLineDefaultData(lineThis, new Entry(0 + startStep, 0));
    setLineDefaultData(lineLast, new Entry(0 + startStep, 0));

    LineDataSet set1, set2;
    if (lineChart.getData() != null &&
        lineChart.getData().getDataSetCount() > 0) {
      set1 = (LineDataSet) lineChart.getData().getDataSetByIndex(0);
      set2 = (LineDataSet) lineChart.getData().getDataSetByIndex(1);
      if (!Util.listIsNull(lineThis)) {
        set1.setValues(lineThis);
      }
      if (!Util.listIsNull(lineLast)) {
        set2.setValues(lineLast);
      }
      lineChart.getData().notifyDataChanged();
      lineChart.notifyDataSetChanged();
    } else {
      // create a dataset and give it a type

      set1 = new LineDataSet(lineThis, "");
      set1.setAxisDependency(YAxis.AxisDependency.LEFT);
      set1.setColor(ContextCompat.getColor(context, R.color.bg_this_year));
      set1.setCircleColor(Color.TRANSPARENT);
      set1.setLineWidth(0.7f);
      set1.setCircleRadius(0f);
      set1.setFillAlpha(100);
//            set1.setFillColor(ColorTemplate.getHoloBlue());
//            set1.setHighLightColor(Color.rgb(244, 117, 117));
      set1.setDrawCircleHole(false);
//            set1.setFillFormatter(new MyFillFormatter(0f));
//            set1.setDrawHorizontalHighlightIndicator(true);
      set1.setVisible(true);
      set1.setDrawValues(true);
      set1.setDrawFilled(false);
      //set1.setCircleHoleColor(Color.WHITE);

      // create a dataset and give it a type
      set2 = new LineDataSet(lineLast, "");
      set2.setAxisDependency(YAxis.AxisDependency.LEFT);
      set2.setColor(ContextCompat.getColor(context, R.color.bg_last_year));
//            set2.setColor(Color.BLACK);
      set2.setCircleColor(Color.TRANSPARENT);
      set2.setLineWidth(0.7f);
      set2.setCircleRadius(0f);
      set2.setFillAlpha(100);
//            set2.setFillColor(Color.RED);
      set2.setDrawCircleHole(false);
      set2.setDrawFilled(false);
      set2.setDrawValues(false);
//            set2.setHighLightColor(Color.rgb(244, 117, 117));
      //set2.setFillFormatter(new MyFillFormatter(900f));

      // create a data object with the datasets
      final LineData data = new LineData(set1, set2);
      data.setDrawValues(false);
//            data.setValueTextColor(ContextCompat.getColor(context, R.color.text_gray));
//            data.setValueTextSize(9f);
      // set data
//            if (Util.isEquals(classType, CADDIE_TAG) && (dateType == QUARTER)) {
//                lineChart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
//                    @Override
//                    public String getFormattedValue(float value, AxisBase axis) {
//                        if (!DataUtil.mapIsNull(names) && names.containsKey((int) value))
//                            return names.get((int) value);
//                        return String.valueOf((int) value);
//                    }
//                });
//            }
      lineChart.setData(data);
    }
  }


  class LinFormat implements IAxisValueFormatter {

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
      String result = "";
      switch (dateType) {
        case CUR:
        case DAY:
          result = String.valueOf((int) (value));
          break;
        case WEEK:
          if (value < weeks.length) {
            result = weeks[(int) value];
          }
          break;
        case MONTH:
          result = String.valueOf((int) value);
          break;
        case QUARTER:
          result = String.valueOf((int) value);
          break;
        case YEAR:
          result = String.valueOf((int) value);
          break;
        default:
          break;
      }
      return result;
    }
  }

  class CharValueListener implements OnChartValueSelectedListener {

    @Override
    public void onValueSelected(Entry e, Highlight h) {
      Log.e("hightlight---------", h.toString());
      // 获取Entry
      int iEntry = (int) e.getX();
      float valEntry = e.getY();
      Log.e("info-------", "e.getX() = " + iEntry + "     e.getY() = " + valEntry);
      // 获取选中value的坐标
      MPPointD p = barChart.getPixelForValues(e.getX(), e.getY(), AxisDependency.LEFT);
      double xValuePos = p.x;
      double yValuePos = p.y;
      Log.e("pos--info--------", "xValuePos = " + xValuePos + "     yValuePos = " + yValuePos);
      long start = startTime;
      long end = endTime;
      String dateString = mDateString;
      /**
       * Highlight.getDataSetIndex():   0为本年  1为上一年
       */
      if (h.getDataSetIndex() > 0) {
        switch (dateType) {
          case CUR:
          case DAY:
            start = DateUtil.getDayBegin(startTime - DateUtil.getOneDay());
            end = DateUtil.getDayEnd(endTime - DateUtil.getOneDay());
            dateString = DateUtil.stampToDate(start, DateUtil.formatYMDBias);
            break;
          case WEEK:
            DateRange range = DateUtil.getLastWeekDateRange(startTime);
            if (null != range) {
              start = range.start;
              end = range.end;
            }
            dateString = new StringBuffer()
                .append(DateUtil.stampToDate(start, DateUtil.formatYMDBias))
                .append("-")
                .append(DateUtil.stampToDate(end, DateUtil.formatMDBias))
                .toString();
            break;
          case MONTH:
            start = DateUtil.getBeginTimeOfLastMonth(startTime);
            end = DateUtil.getEndTimeOfLastMonth(endTime);
            dateString = new StringBuffer()
                .append(DateUtil.stampToDate(start, DateUtil.formatYMDBias))
                .append("-")
                .append(DateUtil.stampToDate(end, DateUtil.formatMDBias))
                .toString();
            break;
          case QUARTER:
            start = DateUtil.getLastQuarter(startTime).start;
            end = DateUtil.getLastQuarter(endTime).end;
            dateString = new StringBuffer()
                .append(DateUtil.stampToDate(start, DateUtil.formatYMDBias))
                .append("-")
                .append(DateUtil.stampToDate(end, DateUtil.formatMDBias))
                .toString();
            break;
          case YEAR:
            start = DateUtil.getBeginTimeOfLastYear(startTime).getTime();
            end = DateUtil.getEndTimeOfLastYear(endTime).getTime();
            dateString = new StringBuffer()
                .append(DateUtil.stampToDate(start, DateUtil.formatYMDBias))
                .append("-")
                .append(DateUtil.stampToDate(end, DateUtil.formatMDBias))
                .toString();
            break;
          default:
            break;
        }
      }
      worker.showDetails(new StatisticsBean.Builder()
          .setBarQueryId(CollectionUtil.getMapString(idMap, iEntry))
          .setBarQueryName(CollectionUtil.getMapString(nameMap, iEntry))
          .setStartTime(start)
          .setEndTime(end)
          .setDateString(h.getDataSetIndex() > 0 ? dateString : mDateString)
          .setBarData(listBarData)
          .setPayCode(CollectionUtil.getMapString(idMap, iEntry))
          .setBussinessCode(pointCode)
          .setPayInCome("")
          .setLineType(TextUtil.contains(nameMap.get(iEntry), "app") ? "ON_LINE" : "OUT_LINE")
          .setReserveType("")
          .setDateUnit(getDateUnit())
          .setSgningId(CollectionUtil.getMapString(idMap, iEntry))
          .setListNameId(listNameId)
          .setListCaddie(h.getDataSetIndex() > 0 ? listCaddieLast : listCaddieThis)
          .build());
    }

    @Override
    public void onNothingSelected() {

    }
  }

  private String getDateUnit() {
    String unit = "Day";
    switch (dateType) {
      case DAY:
        unit = "Day";
        break;
      case WEEK:
        unit = "Week";
        break;
      case MONTH:
        unit = "Month";
        break;
      case QUARTER:
        unit = "Quarter";
        break;
      case YEAR:
        unit = "Year";
        break;
      default:
        break;
    }
    return unit;
  }


  private void initBarChart(final ChartBean bean) {
    barChart.setOnChartValueSelectedListener(new CharValueListener());
    barChart.getDescription().setEnabled(false);
    barChart.setDrawBorders(false);
    // scaling can now only be done on x- and y-axis separately
    barChart.setPinchZoom(false);

    barChart.setDrawBarShadow(false);

    barChart.setDrawGridBackground(false);
    barChart.setTouchEnabled(true);
    barChart.setDragEnabled(true);// 是否可以拖拽
    barChart.setScaleEnabled(true);// 是否可以缩放
//        barChart.setDrawGridBackground(true);
//        barChart.setGridBackgroundColor(ContextCompat.getColor(context, R.color.bg));
//        barChart.setBackgroundColor(Color.WHITE);// 设置整个图表控件的背景
//        barChart.setDrawValueAboveBar(false);//柱状图上面的数值是否在柱子上面
    //是否显示竖直标尺线
    barChart.getXAxis().setDrawGridLines(false);
//        //设置横坐标倾斜角度
//        barChart.getXAxis().setLabelRotationAngle(20);
    //设置动画
    barChart.animateXY(800, 1000);
    barChart.setClickable(true);
    // create a custom MarkerView (extend MarkerView) and specify the layout
    // to use for it
    MyMarkerView mv = new MyMarkerView(context, R.layout.custom_marker_view);
    mv.setChartView(barChart); // For bounds control
    barChart.setMarker(mv); // Set the marker to the chart

    Legend l = barChart.getLegend();
    l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
    l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
    l.setOrientation(Legend.LegendOrientation.VERTICAL);
    l.setDrawInside(true);
//        l.setTypeface(mTfLight);
    l.setYOffset(0f);
    l.setXOffset(10f);
    l.setYEntrySpace(0f);
    l.setTextSize(8f);
    l.setEnabled(false);

    XAxis xAxis = barChart.getXAxis();
//        xAxis.setTypeface(mTfLight);
    xAxis.setGranularity(1f);
    xAxis.setCenterAxisLabels(true);
    xAxis.setLabelCount(bean.barXLableCount);
//        xAxis.setAxisMaximum(bean.barXMax);
    xAxis.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
    xAxis.setSpaceMin(10f);
    YAxis leftAxis = barChart.getAxisLeft();
//        leftAxis.setTypeface(mTfLight);
//        leftAxis.setValueFormatter(new LargeValueFormatter());
    leftAxis.setDrawGridLines(true);
    leftAxis.setSpaceTop(35f);
    leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
//        leftAxis.setAxisMaximum(bean.barLeftMax);
    leftAxis.setDrawAxisLine(false);
    leftAxis.setDrawZeroLine(false);
    leftAxis.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
    leftAxis.setLabelCount(bean.barYLableCount, true);
//        MyYAxisValueFormatter custom = new MyYAxisValueFormatter();
//        leftAxis.setValueFormatter(custom);
    barChart.getAxisRight().setEnabled(false);


  }

  public Map<Integer, String> nameMap = new ArrayMap<>();
  public Map<Integer, String> idMap = new ArrayMap<>();
  public List<ListBean> listNameId = new ArrayList<>();
  public List<CaddieHistory> listCaddieThis = new ArrayList<>();
  public List<CaddieHistory> listCaddieLast = new ArrayList<>();

  private List<ChartData> listBarData = new ArrayList<>();

  private long startTime;
  private long endTime;

  private void setBarChartData(ChartBean bean) {
    if (bean == null) {
      return;
    }
    ArrayList<BarEntry> barThis = bean.BarthisVals;
    ArrayList<BarEntry> barLast = bean.BarlastVals;
    nameMap.clear();
    idMap.clear();
    listBarData.clear();
    listNameId.clear();
    listCaddieThis.clear();
    listCaddieLast.clear();
    if (null != bean.listCaddieThis) {
      listCaddieThis.addAll(bean.listCaddieThis);
    }
    if (null != bean.listCaddieLast) {
      listCaddieLast.addAll(bean.listCaddieLast);
    }
    if (null != bean.listNameId) {
      listNameId.addAll(bean.listNameId);
    }
    if (Util.listIsNull(listNameId) && !CollectionUtil.mapIsNull(bean.nameIdMap)) {
      ListBean b;
      for (Map.Entry<String, String> me : bean.nameIdMap.entrySet()) {
        b = new ListBean();
        b.idForName = me.getValue();
        b.nameForShow = me.getKey();
        listNameId.add(b);
      }
    }
    if (!CollectionUtil.mapIsNull(bean.BarMap)) {
      nameMap.putAll(bean.BarMap);
      Log.e("name not null:", "---------------------------");
      for (Map.Entry<Integer, String> me : nameMap.entrySet()) {
        Log.e(me.getKey() + "---------", me.getValue() + "---------");
      }
    }
    if (!CollectionUtil.mapIsNull(bean.idMap)) {
      idMap.putAll(bean.idMap);
    }
    if (!Util.listIsNull(bean.listBarData)) {
      listBarData.addAll(bean.listBarData);
    }
    startTime = bean.startTime;
    endTime = bean.endTime;
    if (Util.listIsNull(barThis)
        && Util.listIsNull(barLast)) {
      showError(ErrorUtil.NODATA);
      return;
    }
    if (DataUtil.mapIsNull(nameMap)) {
      showError(ErrorUtil.NODATA);
      return;
    }
    switch (mType) {
      case DataManager.STATISTICS_BUSINESS_ALL:
        ViewUtils.setText(barInfoTv, "点击查看详情");
        break;
      case DataManager.STATISTICS_CADDIE_ALL:
        ViewUtils.setText(barInfoTv, "点击类型查看详情");
        break;
      case DataManager.STATISTICS_BOOK_ALL:
        ViewUtils.setText(barInfoTv, "点击类型查看详情");
        break;
      case DataManager.STATISTICS_BILL_ALL:
        ViewUtils.setText(barInfoTv, "点击名字查看详情");
        break;
      case DataManager.STATISTICS_PLAYER_ALL:
        ViewUtils.setText(barInfoTv, "点击类型查看详情");
        break;
      default:
        ViewUtils.setText(barInfoTv, "点击查看详情");
        break;
    }
    ViewUtils.setVisible(barInfoTv, true);
    setBarDefaultData(barThis, new BarEntry(0 + startStep, 0));
    setBarDefaultData(barLast, new BarEntry(0 + startStep, 0));
//        float groupSpace = 0.5f;
//        float barSpace = 0f; // x4 DataSet
//        float barWidth = 0.25f; // x4 DataSet
    float groupSpace = 0.75f;
    float barSpace = 0f; // x4 DataSet
    float barWidth = 0.125f; // x4 DataSet
    // (0.2 + 0.03) * 4 + 0.08 = 1.00 -> interval per "group"
//        groupSpace = (barChart.getWidth()- barChart.getAxisLeft().getMaxWidth())/listPayWayName.size();
//        barWidth = (1 - groupSpace) / listPayWayName.size() - barSpace;
    int groupCount = nameMap.size();
    if (groupCount == 1) {
      groupSpace = 0.96f;
      barWidth = 0.02f;
    } else if (groupCount > 1 && groupCount < 4) {
      groupSpace = 0.9f;
      barWidth = 0.05f;
    } else if (groupCount >= 4 && groupCount < 6) {
      groupSpace = 0.84f;
      barWidth = 0.08f;
    }

    int endYear = startStep + groupCount;
    BarDataSet set1, set2;

    if (barChart.getData() != null && barChart.getData().getDataSetCount() > 0) {
      set1 = (BarDataSet) barChart.getData().getDataSetByIndex(0);
      set2 = (BarDataSet) barChart.getData().getDataSetByIndex(1);
      set1.setValues(barThis);
      set2.setValues(barLast);
      barChart.getData().notifyDataChanged();
      barChart.notifyDataSetChanged();

    } else {
      // create 4 DataSets
      set1 = new BarDataSet(barThis, "Company A");
      set1.setColor(ContextCompat.getColor(context, R.color.bg_blue));
      set1.setDrawValues(false);
      set2 = new BarDataSet(barLast, "Company B");
      set2.setColor(ContextCompat.getColor(context, R.color.bg_blue_deep));
      set2.setDrawValues(false);
      BarData data = new BarData(set1, set2);
      data.setValueFormatter(new LargeValueFormatter());
      barChart.setData(data);
    }

//        // specify the width each bar should have
    barChart.getBarData().setBarWidth(barWidth);
//
//        // restrict the x-axis range
    barChart.getXAxis().setAxisMinimum(startStep);
////        barChart.getBarData().setBarSpacePercent(50f);
////         barData.getGroupWith(...) is a helper that calculates the width each group needs based on the provided parameters
    barChart.getXAxis().setAxisMaximum(startStep + barChart.getBarData()
        .getGroupWidth(groupSpace, barSpace) * groupCount);
////        barChart.groupBars(startStep, groupSpace, barSpace);
    barChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
    barChart.getXAxis().setLabelCount(nameMap.size());
    barChart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
      @Override
      public String getFormattedValue(float value, AxisBase axis) {
        String result = "";
        int index = (int) value;
        if (index < 1000) {
          index = 1000;
        }
        if (index > 1000 + nameMap.size()) {
          index = 1000 + nameMap.size();
        }
        if (nameMap.containsKey(index)) {
          result = nameMap.get(index);
          if (!Util.isNull(result) && result.length() > 4) {
            return result.substring(0, 4);
          }
        }
        return result;
      }
    });
    barChart.groupBars(startStep, groupSpace, barSpace);
    setChartData(groupCount);
    barChart.animateX(1500); // 立即执行的动画,x轴
    barChart.invalidate();

  }

  private void setChartData(int xCount) {
    Matrix m = new Matrix();
    m.postScale(scaleNum(xCount), 1f);//两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
    barChart.getViewPortHandler().refresh(m, barChart, true);//将图表动画显示之前进行缩放
  }

  //30个横坐标时，缩放4f是正好的。
  private float scalePercent = 5f / 30f;

  private float scaleNum(int xCount) {
    return xCount * scalePercent;
  }


}
